package com.jogern.weightlib;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.support.annotation.DrawableRes;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 图片文本View（上面是图片下是文本描述）
 * Created by jogern on 2016/8/30 0030.
 */

public class ImgTextView extends LinearLayout {
    private ImageView mIconView;
    private TextView mDescView;

    public ImgTextView(Context context) {
        super(context);
        initView(context);
    }

    public ImgTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
        initAttr(context, attrs, 0);
    }

    public ImgTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
        initAttr(context, attrs, defStyleAttr);
    }

    private void initAttr(Context context, AttributeSet attrs, int defStyleAttr) {
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ImgTextView);

        int resId = ta.getResourceId(R.styleable.ImgTextView_img_res, 0);
        setImageResource(resId);
        String string = ta.getString(R.styleable.ImgTextView_textStr);
        setNameText(string);

        ta.recycle();
    }


    private void initView(Context context) {
//        float density = getResources().getDisplayMetrics().density;
        setOrientation(VERTICAL);
        LayoutParams iconParams = new LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f);
        iconParams.gravity = Gravity.CENTER_HORIZONTAL;
        mIconView = new ImageView(context);
        addView(mIconView, iconParams);

        LayoutParams nameParams = new LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
//        nameParams.topMargin = (int) (density * 3f + 0.5f);
        mDescView = new TextView(context);
//        mDescView.setTextSize(18);
        mDescView.setTextColor(Color.WHITE);
        mDescView.setSingleLine();
        mDescView.setGravity(Gravity.CENTER_HORIZONTAL);
        addView(mDescView, nameParams);
    }

    public void setImageResource(@DrawableRes int resId) {
        mIconView.setImageResource(resId);
    }

    public void setNameText(CharSequence text) {
        mDescView.setText(text);
    }

    public void setNameColorText(int color, CharSequence text) {
        mDescView.setTextColor(color);
        setNameText(text);
    }

    public void setNameSizeText(float size, CharSequence text) {
        mDescView.setTextSize(size);
        setNameText(text);
    }

    public void setNameSizeColorText(float size, int color, CharSequence text) {
        mDescView.setTextSize(size);
        setNameColorText(color, text);
    }
}
